package com.ruoyi.mongo.souce;

import org.bson.Document;

//import com.mongodb.MongoClient;
// import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

/**
 * @Description: 创建MongoDB池连-使用用户认证
 * @ClassName: MongoDBAuthPoolUtil
 * @author syc
 * @date: 2022年5月25日 上午10:44:57
 */
public class MongoDB04AuthPoolUtil {
//    private static MongoClient client = null;
//    static{
//        if(client == null) {
//            MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
//            builder.connectionsPerHost(10); // 每个地址最大连接数
//            builder.connectTimeout(5000); // 链接超时时间 (单位毫秒)
//            builder.socketTimeout(5000);  // 设置读写操作超时时间
//            MongoCredential credential = MongoCredential.createCredential("root","admin","sykj85575700".toCharArray());
//            ServerAddress address = new ServerAddress("192.168.1.125",27017);
//            client = new MongoClient(address,credential,builder.build());
//        }
//    }

    // 获取MongoDB数据库
    public static MongoDatabase getDatabase(String dbName) {
       // return client.getDatabase(dbName);
    	return null;
    }

    // 获取MongiDb中的集合
    public static MongoCollection<Document> getCollection(String dbName , String collName) {
        MongoDatabase database = getDatabase(dbName);
        return database.getCollection(collName);
    }
    // 创建集合
    public static void createCollection(String dbName,String collName) {
        MongoDatabase database = getDatabase(dbName);
        database.createCollection(collName);
    }
    // 删除集合
    public static void dropCollection(MongoCollection<Document> coll){
       coll.drop();
    }
    
    /**
     * @Description:测试 
     * @author syc
     * @date: 2022年5月25日 上午10:27:05
     */
    public static void main(String[] args) {

    	MongoCollection<Document>	collection = MongoDB04AuthPoolUtil.getCollection("test", "test_user");
    	 FindIterable<Document> iterable = collection.find();
         MongoCursor<Document> cursor = iterable.iterator();
         while(cursor.hasNext()){
            // 每掉一次next移动以下指针
            Document docu = cursor.next();
            System.out.println(docu.get("name")+"\t" + docu.get("age") + "\t" + docu.get("sex") + "\t" + docu.get("secrets"));
         }
	}

}
